import service from "../../service/services";

//处理当前权限下的菜单及按钮
var dealMenuList = function(list) {
	if (!list) return;
	let btnsList = []; //当前权限下的按钮集合
	let menuList = []; //当前权限下的菜单集合
	list.forEach(item => {
		let param = {
			path: item.href,
			meta: { title: item.title },
			children: null
		};
		if (item.children.length > 0) {
			param.children = [];
			item.children.forEach(item2 => {
				//按钮
				if (item2.data && item2.data.type == 1) {
					btnsList.push(item2.href);
				} else {
					let param2 = {
						path: item2.href,
						meta: { title: item2.title }
					};
					param.children.push(param2);
				}
			});
		}
		menuList.push(param);
	});
	return { btnsList, menuList };
};

let getItemFromLocalStorage = function(key) {
	let value = localStorage.getItem(key);
	if (value) return JSON.parse(value);
	else return null;
};

const menu = {
	state: {
		currentBtns: getItemFromLocalStorage("currentBtns") || [],
		currentMenus: getItemFromLocalStorage("currentMenuList") || [], //当前登录的菜单
		allMenus: [] //所有菜单集合
	},
	actions: {
		//获取当前登录人的菜单
		getCurrentMenu({ commit, dispatch }, username) {
			return new Promise(resolve => {
				service.user.getCurrentMenu(username).then(res => {
					const data = res.data;
					const { btnsList, menuList } = dealMenuList(data);
					commit("SET_MENU", menuList);
					commit("SET_BTNS", btnsList);
					resolve(menuList);
				});
			});
		},
		//获取所有系统菜单
		getAllMenu({ commit, dispatch }) {
			return new Promise(resolve => {
				service.user.getmenu().then(res => {
					const data = res.data.data;
					resolve(menu);
				});
			});
		}
	},
	mutations: {
		SET_MENU: (state, menus) => {
			state.currentMenus = menus;
			localStorage.setItem("currentMenuList", JSON.stringify(menus));
		},
		SET_BTNS: (state, btns) => {
			state.currentBtns = btns;
			localStorage.setItem("currentBtns", JSON.stringify(btns));
		}
	},
	getters: {
		// ...
		isPermissionsBtn: state => value => {
			state.currentBtns.incl;
			let flag = state.currentBtns.includes(value);
			// console.log("flag", flag);
			return flag;
		}
	}
};
export default menu;
